<?php
/**
 * Do the Company Merging
 * 
 * 
 */

use Hive\Ressource\Experience;
use Hive\Company;
$xview = Xview::instance();
/* @var $contact Hive\Company */
$company = $xview->component('company', 'object');

$codes = $xview->val('checked');
if(!empty($codes)) {
	$codes = json_decode($codes,true);
}

$mode = $xview->val('mode');

if(!empty($codes) && is_array($codes)) {
	$targetCpId = $company->getId();
	foreach($codes as $code) {
		if(empty($code)) {
			continue;
		}
		try {
			$toBeMergeCompany = \Fox\Dao::load(Company::className(),$code);
			$expInfos = Fox\Dao::infos(Experience::className());
			$handle = $expInfos->handle();
			$handle->beginTransaction();
			// Update All reference
			$handle->update($expInfos->tableName(),array('compid'=>$targetCpId),array('compid'=>$code));
			$handle->commit();
			Fox\Message::Success(Msg(Hive::BUNDLE,Hive::COMPANY_X_HAS_BEEN_MERGE_INTO_Y,
									$toBeMergeCompany->name(),
									$company->name()));
			if($mode == 'delete') {
				$toBeMergeCompany->delete();
			} else {
				
			}
		} catch(Fox\Object\Exception\NotExist $e) {
			Fox\Message::Error($e);
			continue;
		}
	}
}
return $xview->messages(true,true);